<template>
  <div class="dashboard">
    <h2>数据统计</h2>
    
    <div class="data-cards">
      <el-card class="data-card">
        <template #header>
          <div class="card-header">
            <span>今日订单</span>
            <el-tag>{{ stats.todayOrders }}</el-tag>
          </div>
        </template>
        <div class="amount">¥{{ stats.todayAmount }}</div>
        <div class="comparison">
          较昨日
          <span :class="stats.orderGrowth >= 0 ? 'up' : 'down'">
            {{ Math.abs(stats.orderGrowth) }}%
          </span>
        </div>
      </el-card>
      
      <el-card class="data-card">
        <template #header>
          <div class="card-header">
            <span>商品总数</span>
          </div>
        </template>
        <div class="amount">{{ stats.totalProducts }}</div>
        <div class="sub-info">
          在售: {{ stats.activeProducts }}
        </div>
      </el-card>
      
      <el-card class="data-card">
        <template #header>
          <div class="card-header">
            <span>待处理</span>
          </div>
        </template>
        <div class="pending-items">
          <div class="item">
            <span>待发货</span>
            <el-tag type="warning">{{ stats.pendingShipments }}</el-tag>
          </div>
          <div class="item">
            <span>退款申请</span>
            <el-tag type="danger">{{ stats.pendingRefunds }}</el-tag>
          </div>
        </div>
      </el-card>
    </div>
    
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>销售趋势</span>
          <el-radio-group v-model="timeRange" size="small">
            <el-radio-button label="week">近7天</el-radio-button>
            <el-radio-button label="month">近30天</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div class="chart-container">
        <v-chart :option="chartOption" autoresize />
      </div>
    </el-card>
    
    <div class="data-tables">
      <el-card class="table-card">
        <template #header>
          <div class="card-header">
            <span>热销商品</span>
          </div>
        </template>
        <el-table :data="topProducts" style="width: 100%">
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="sales" label="销量" width="120" />
          <el-table-column prop="amount" label="销售额" width="120">
            <template #default="scope">
              ¥{{ scope.row.amount }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <el-card class="table-card">
        <template #header>
          <div class="card-header">
            <span>最新订单</span>
          </div>
        </template>
        <el-table :data="recentOrders" style="width: 100%">
          <el-table-column prop="id" label="订单号" width="180" />
          <el-table-column prop="createTime" label="下单时间" width="180" />
          <el-table-column prop="amount" label="金额" width="120">
            <template #default="scope">
              ¥{{ scope.row.amount }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              {{ orderStatusText[scope.row.status] }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'

use([
  CanvasRenderer,
  LineChart,
  GridComponent,
  TooltipComponent,
  LegendComponent
])

const store = useStore()
const timeRange = ref('week')
const stats = ref({})
const topProducts = ref([])
const recentOrders = ref([])
const chartOption = ref({})

const orderStatusText = {
  PENDING: '待付款',
  PAID: '待发货',
  SHIPPED: '待收货',
  COMPLETED: '已完成',
  CANCELLED: '已取消'
}

const loadDashboardData = async () => {
  try {
    const [statsData, salesData] = await Promise.all([
      store.dispatch('shop/getShopStats'),
      store.dispatch('shop/getSalesData', { range: timeRange.value })
    ])
    
    stats.value = statsData
    updateChartOption(salesData)
  } catch (error) {
    ElMessage.error('加载统计数据失败')
  }
}

const loadTopProducts = async () => {
  try {
    const data = await store.dispatch('shop/getTopProducts')
    topProducts.value = data
  } catch (error) {
    ElMessage.error('加载热销商品失败')
  }
}

const loadRecentOrders = async () => {
  try {
    const data = await store.dispatch('shop/getRecentOrders')
    recentOrders.value = data
  } catch (error) {
    ElMessage.error('加载最新订单失败')
  }
}

const updateChartOption = (data) => {
  chartOption.value = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '销售额',
        type: 'line',
        data: data.amounts,
        smooth: true,
        areaStyle: {}
      }
    ]
  }
}

watch(timeRange, () => {
  loadDashboardData()
})

onMounted(() => {
  loadDashboardData()
  loadTopProducts()
  loadRecentOrders()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.data-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.data-card {
  .amount {
    font-size: 24px;
    font-weight: bold;
    margin: 10px 0;
  }
  
  .comparison {
    color: #666;
    .up { color: #67c23a; }
    .down { color: #f56c6c; }
  }
  
  .pending-items {
    .item {
      display: flex;
      justify-content: space-between;
      margin: 10px 0;
    }
  }
}

.chart-card {
  margin-bottom: 20px;
  
  .chart-container {
    height: 400px;
  }
}

.data-tables {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 